package main

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"time"

	"github.com/gorilla/websocket"
)

type DebugInfo struct {
	QPS int32 `json:"qps"`
	RTT int32 `json:"rtt"`
}

var content []byte

func init() {
	var err error
	content, err = ioutil.ReadFile("debug.html")
	if err != nil {
		panic(err)
	}
}

func debug(w http.ResponseWriter, r *http.Request) {
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			// without check
			return true
		},
	}
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	tick := time.NewTicker(time.Second)
	for {
		select {
		case <-tick.C:
			info := &DebugInfo{}
			info.QPS = rand.Int31n(10)
			info.RTT = rand.Int31n(10) + 10
			msg, err := json.Marshal(info)
			if err != nil {
				return
			}
			err = c.WriteMessage(websocket.TextMessage, msg)
			if err != nil {
				return
			}
		}
	}
}

func index(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, string(content))
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/debug", debug)
	mux.HandleFunc("/", index)
	if err := http.ListenAndServe(":19891", mux); err != nil {
		log.Fatal(err)
	}
}
